package com.syl.upimg.service.impl;

import com.syl.upimg.bean.BaiDuBean;
import com.syl.upimg.enums.ImageUploadTypeEnum;
import com.syl.upimg.service.BaseUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 百度百家号羊毛
 *
 * @author syl
 * @create 2019-08-02 11:04
 **/
@Service
public class BdFleece implements BaseUpload {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public RestTemplate createRestTemplate() {
        return restTemplate;
    }

    @Override
    public String[] getLimit() {
        return new String[]{"jpg", "png", "bmp"};
    }

    @Override
    public String getUrl() {
        return "https://baijiahao.baidu.com/builderinner/api/content/file/upload";
    }

    @Override
    public LinkedMultiValueMap<String, Object> getParam(FileSystemResource file, String fileName, String fileType) {
        LinkedMultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("media", file);
        multiValueMap.add("no_compress", 1);
        multiValueMap.add("id", "WU_FILE_0");
        multiValueMap.add("is_avatar", "0");
        multiValueMap.add("type", getMimeType(file));
        multiValueMap.add("name", file.getFilename());
        return multiValueMap;
    }

    @Override
    public HttpHeaders getDefaultHeader() {
        return getDefaultHeader("https://baijiahao.baidu.com", "https://baijiahao.baidu.com/builder/app/register?type=individual");
    }

    public BaiDuBean upload(String filePath) throws IOException {
        return this.upload(filePath, false);
    }

    public BaiDuBean upload(String filePath, boolean delete) throws IOException {
        BaiDuBean baiDuBean = this.upload(filePath, BaiDuBean.class, delete);
        BaiDuBean.Result result = baiDuBean.getResult();
        if (result != null) baiDuBean.setBaseUrl(result.getHttpsUrl());
        baiDuBean.setImageUploadTypeEnum(ImageUploadTypeEnum.BD);
        return baiDuBean;
    }

}
